package cvi.com.reader.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cvi.com.reader.R;
import cvi.com.reader.adapter.ChartListAdapter;
import cvi.com.reader.base.BaseActivity;
import cvi.com.reader.bean.ChartDataBean;
import cvi.com.reader.bean.constant;
import cvi.com.reader.network.DefaultObserver;
import cvi.com.reader.network.NetWorkManager;
import cvi.com.reader.tool.refresh.CustomRefreshFooter;
import cvi.com.reader.tool.refresh.CustomRefreshHeader;
import cvi.com.reader.widgets.MultiStateView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by 梅涛 on 2020/7/24.
 * <p>
 * 排行榜页面
 */

public class ChartsDataActivity extends BaseActivity implements View.OnClickListener, ChartListAdapter.AuditionClickInterface {


    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.tittle)
    TextView tittle;
    @BindView(R.id.mylistview)
    ListView mylistview;
    @BindView(R.id.stateView)
    MultiStateView stateView;
    @BindView(R.id.no_data)
    TextView noData;
    @BindView(R.id.smartRefreshLayout_home)
    SmartRefreshLayout smartRefreshLayout;
    private int material_id = -1;
    private ChartListAdapter chartListAdapter = null;
    private List<ChartDataBean.DataBean> dataBeanList = new ArrayList<>();
    private String smaterial_name;
    private MediaPlayer mediaPlayer = new MediaPlayer();//实例化MediaPlayer类
    private MyReceiver myReceiver;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_charts_data;
    }

    @Override
    protected void initView() {
        initSmartRefreshLayout();
        stateView.getBackground().setAlpha(153);
        back.setOnClickListener(this);
        material_id = getIntent().getIntExtra("material_id", -1);
        smaterial_name = getIntent().getStringExtra("material_name");
        tittle.setText("《" + smaterial_name + "》" + "-" + "排行榜");
    }

    @Override
    protected void initData() {
        //绑定生命周期
        NetWorkManager.getInstance().getNetWorkApiService().getRankData(material_id).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(ChartsDataActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        stateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        //获取热门数据
                        setChartData(response);
                        smartRefreshLayout.finishRefresh(true);

                    }
                });
    }

    @Override
    protected void extrasDoSome(Bundle extras) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        //注册广播接收器
        myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(constant.CHARTS_MYRECEIVER);
        registerReceiver(myReceiver, intentFilter);
    }

    //初始化下拉刷新控件
    private void initSmartRefreshLayout() {
        smartRefreshLayout.setEnableLoadmore(false);
        smartRefreshLayout.setRefreshHeader(new CustomRefreshHeader(ChartsDataActivity.this));
        smartRefreshLayout.setRefreshFooter(new CustomRefreshFooter(ChartsDataActivity.this, "加载中…"));
        smartRefreshLayout.setEnableScrollContentWhenLoaded(true);//是否在加载完成时滚动列表显示新的内容
        smartRefreshLayout.setEnableFooterFollowWhenLoadFinished(true);
        smartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //  presenter.onLoadMore();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                dataBeanList.clear();
                initData();
            }
        });

    }

    private void setChartData(JSONObject response) {
        JSONArray array = response.getJSONArray("data");
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = (JSONObject) array.get(i);     //将array中的数据进行逐条转换
            ChartDataBean.DataBean dataBean = (ChartDataBean.DataBean) JSONObject.toJavaObject(object, ChartDataBean.DataBean.class);  //通过JSONObject.toBean()方法进行对象间的转换
            dataBeanList.add(dataBean);
        }
        Log.d("fdfdf11111", dataBeanList.size() + "");
        if (0 == dataBeanList.size()) {
            stateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
            smartRefreshLayout.setEnableRefresh(false);
            // noData.setVisibility(View.VISIBLE);
            Log.d("fdfdf2222", dataBeanList.size() + "");
        } else {
            smartRefreshLayout.setEnableRefresh(true);
            Log.d("fdfdf333333", dataBeanList.size() + "");
            chartListAdapter = new ChartListAdapter(ChartsDataActivity.this, dataBeanList);
            mylistview.setAdapter(chartListAdapter);
            chartListAdapter.notifyDataSetChanged();
            noData.setVisibility(View.GONE);
        }
        mylistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ChartDataBean.DataBean dataBean = (ChartDataBean.DataBean) adapterView.getAdapter().getItem(i);
                Hawk.put("ChartDataBean", dataBean);
                //  素材类型 0:文本类型 、1:绘本类型、2:影视类型
                if ("0".equals(dataBean.getMaterial().getType())) {
                    Intent intent = new Intent(ChartsDataActivity.this, AuditionActivity.class);
                    startActivity(intent);
                } else if ("1".equals(dataBean.getMaterial().getType())) {
                    Intent intent = new Intent(ChartsDataActivity.this, PictureBookAuditionActivity.class);
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    public void onAudition(String url) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
        }
    }

    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            dataBeanList.clear();
            initData();
        }
    }
}
